import { computedNavData } from '@/core';
import { IDrtabStore } from '@/core/interface/widgets/store';
import {
	DrtabActionType,
	IDrtabAbility,
	IDrtabController,
	IDrtabControllerParams,
	IDrtabModel,
	IParam,
} from '../../interface';
import { DECtrlController } from './de-ctrl-controller';

/**
 * 数据关系分页部件控制器
 *
 * @export
 * @class DrtabController
 * @extends {WidgetsController<IDrtabStore>}
 * @implements {IDrtabController}
 * @template T
 */
export class DrtabController
	extends DECtrlController<DrtabActionType, IDrtabStore, IDrtabAbility>
	implements IDrtabController<IDrtabStore, IDrtabAbility>
{
	/**
	 * Creates an instance of DrtabController.
	 * @param {IDrtabControllerParams<DrtabActionType, IDrtabAbility>} params
	 * @memberof DrtabController
	 */
	public constructor(
		params: IDrtabControllerParams<DrtabActionType, IDrtabAbility>
	) {
		super(params);
		this.ctrlInit(params);
	}

	/**
	 * 处理部件初始化
	 *
	 * @protected
	 * @param {IDrtabControllerParams<DrtabActionType, IDrtabAbility>} params
	 * @memberof DrtabController
	 */
	protected processCtrlInit(
		params: IDrtabControllerParams<DrtabActionType, IDrtabAbility>
	) {
		super.processCtrlInit(params);
		const model = this.getModel<IDrtabModel>();
		Object.assign(this.store, {
			pages: model.pages,
			selectItem: null,
		});
	}

	/**
	 * @description 处理选中
	 * @param {IParam} item
	 * @memberof DrtabController
	 */
	public handleSelectChange(item: IParam) {
		this.store.selectItem = item;
		this.emit('selectionChange', [item]);
	}

	/**
	 * @description 处理表单数据
	 * @param {IParam} data
	 * @memberof DrtabController
	 */
	public handleFormChange(data: IParam) {
		if (data && Object.is(data.srfuf, '1')) {
			this.model.pages.forEach((item: any) => {
				// 取消禁用
				item.disabled = false;
				// 设置导航参数
				if (item.localContext) {
					item.localContext = computedNavData(
						data,
						this.store.context,
						this.store.viewParams,
						item.localContext
					);
				}
				if (item.localParam) {
					item.localViewParam = computedNavData(
						data,
						this.store.context,
						this.store.viewParams,
						item.localParam
					);
				}
			});
		} else {
			this.model.pages.forEach((item: any) => {
				item.disabled = true;
			});
		}
	}

	/**
	 * @description 获取能力
	 * @return {*}  {IDrtabAbility}
	 * @memberof DrtabController
	 */
	getAbility(): IDrtabAbility {
		return {
			...super.getAbility(),
			handleFormChange: this.handleFormChange.bind(this),
		};
	}
}
